package se.hrbustrc.hlgshopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import se.hrbustrc.hlgshopping.entity.Cart;
import se.hrbustrc.hlgshopping.entity.Product;
import se.hrbustrc.hlgshopping.entity.Prosku;
import se.hrbustrc.hlgshopping.mapper.ProductMapper;
import se.hrbustrc.hlgshopping.mapper.ProskuMapper;
import se.hrbustrc.hlgshopping.service.CartService;
import se.hrbustrc.hlgshopping.mapper.CartMapper;
import org.springframework.stereotype.Service;
import se.hrbustrc.hlgshopping.utils.Result;
import se.hrbustrc.hlgshopping.controller.CartController.CartMergeRequest;

import java.math.BigDecimal;
import java.util.List;

/**
* @author qianbimo
* @description 针对表【tb_cart(购物车表)】的数据库操作Service实现
* @createDate 2025-09-10 09:26:55
*/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart>
    implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ProskuMapper proskuMapper;
    @Override
    public Result cartList(long userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fUserId", userId);
        List<Cart> cartList = cartMapper.selectList(queryWrapper);
        
        Result result = new Result();
        result.ok(cartList);
        return result;
    }
    @Override
    public boolean addCart(long skuId, int pnum, Long userId) {

        Cart cart = new Cart();
        Prosku prosku = proskuMapper.selectById(skuId);
        Long pid = prosku.getPid();
        Product product = productMapper.selectById(pid);
        cart.setUserid(userId); // 使用从token中获取的用户ID
        cart.setProductid(pid);
        cart.setSkuid(skuId);
        cart.setName(product.getPname());
        cart.setAttrstext(prosku.getSkuname());
        cart.setPicture(product.getPimage1());
        cart.setPrice(BigDecimal.valueOf(prosku.getPricesell()));//商品价格
        BigDecimal nowPrice = BigDecimal.valueOf(prosku.getPricesell()*pnum);
        cart.setNowprice(nowPrice);//当前售价
        cart.setNoworiginalprice(BigDecimal.valueOf(prosku.getPriceorigion()));

        // 检查该用户购物车中是否已存在该商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fUserId", userId);
        queryWrapper.eq("fSKUId", skuId);
        Cart cartExists = cartMapper.selectOne(queryWrapper);
        
        if(cartExists == null){
            cart.setCount(pnum);
            cartMapper.insert(cart);
            return true;
        }
        else {
            cartExists.setCount(cartExists.getCount() + pnum);
            return cartMapper.updateById(cartExists) > 0;
        }
    }
    @Override
    public boolean updateCartItemCount(long skuId, int newCount, Long userId) {
        // 查询购物车中是否存在该商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fUserId", userId);
        queryWrapper.eq("fSKUId", skuId);
        Cart existingCart = cartMapper.selectOne(queryWrapper);

        // 如果购物车中存在该商品
        if (existingCart != null) {
            // 更新商品数量
            existingCart.setCount(newCount);
            // 保存更新
            return cartMapper.updateById(existingCart) > 0;
        }

        // 如果购物车中不存在该商品，返回false
        return false;
    }
    @Override
    public boolean deleteCartItems(List<Long> ids, Long userId) {
        try {
            // 删除指定用户和ID的购物车项
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("FSkuId", ids);
            queryWrapper.eq("FUserId", userId);
            System.out.println("执行删除操作，用户ID: " + userId + "，购物车项ID: " + ids);
            int deletedCount = cartMapper.delete(queryWrapper);
            System.out.println("实际删除了 " + deletedCount + " 条记录");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean mergeCart(List<Cart> cartItems, Long userId) {
        try {
            // 实现购物车合并逻辑
            for (Cart cartItem : cartItems) {
                // 检查购物车中是否已存在该商品
                QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("fUserId", userId);
                queryWrapper.eq("fSKUId", cartItem.getSkuid());
                Cart existingCart = cartMapper.selectOne(queryWrapper);

                if (existingCart != null) {
                    // 如果存在，更新数量
                    existingCart.setCount(existingCart.getCount() + cartItem.getCount());
                    cartMapper.updateById(existingCart);
                } else {
                    // 如果不存在，添加新记录
                    cartItem.setUserid(userId);
                    cartMapper.insert(cartItem);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean mergeCartFromFrontend(List<CartMergeRequest> cartItems, Long userId) {
        try {
            // 实现购物车合并逻辑，处理前端传来的数据格式
            for (CartMergeRequest cartItem : cartItems) {
                // 检查购物车中是否已存在该商品
                QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("fUserId", userId);
                queryWrapper.eq("fSKUId", cartItem.getSkuId());
                Cart existingCart = cartMapper.selectOne(queryWrapper);

                if (existingCart != null) {
                    // 如果存在，更新数量
                    existingCart.setCount(existingCart.getCount() + cartItem.getCount());
                    cartMapper.updateById(existingCart);
                } else {
                    // 如果不存在，添加新记录
                    Cart newCartItem = new Cart();
                    newCartItem.setUserid(userId);
                    newCartItem.setSkuid(cartItem.getSkuId());
                    newCartItem.setName(cartItem.getName());
                    newCartItem.setPicture(cartItem.getPicture());
                    newCartItem.setCount(cartItem.getCount());
                    
                    // 处理价格字段
                    if (cartItem.getPrice() != null) {
                        BigDecimal price = new BigDecimal(cartItem.getPrice());
                        newCartItem.setPrice(price);
                        // 设置当前价格为单价*数量
                        newCartItem.setNowprice(price.multiply(new BigDecimal(cartItem.getCount())));
                    }
                    
                    // 设置默认值
                    newCartItem.setSelected(cartItem.getSelected() != null && cartItem.getSelected() ? 1 : 0);
                    newCartItem.setIseffective(1); // 默认有效
                    
                    // 查询商品信息以填充其他字段
                    Prosku prosku = proskuMapper.selectById(cartItem.getSkuId());
                    if (prosku != null) {
                        Long productId = prosku.getPid();
                        newCartItem.setProductid(productId);
                        newCartItem.setAttrstext(prosku.getSkuname());
                        
                        Product product = productMapper.selectById(productId);
                        if (product != null) {
                            if (prosku.getPriceorigion() != null) {
                                newCartItem.setNoworiginalprice(BigDecimal.valueOf(prosku.getPriceorigion()));
                            }
                            newCartItem.setStock(prosku.getStocknum());
                            newCartItem.setPostfee(BigDecimal.ZERO);
                        }
                    }
                    
                    cartMapper.insert(newCartItem);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}




